// Global variables
let currentFiles = [];
let uploadProgress = {};
let isBatchMode = false;
let selectedFiles = new Set();
let isMonitoring = false;
let eventSource = null;
let isMonitoringMode = false;

// Toggle upload section with smooth animation
function toggleUpload() {
    const uploadContent = document.getElementById('uploadContent');
    const uploadToggle = document.getElementById('uploadToggle');
    
    if (uploadContent.style.display === 'none') {
        // 展开 - 使用弹性动画
        uploadContent.style.display = 'block';
        uploadContent.style.opacity = '0';
        uploadContent.style.transform = 'translateY(-20px) scaleY(0.9)';
        uploadContent.style.transformOrigin = 'top';
        
        // 强制重绘
        uploadContent.offsetHeight;
        
        // 应用动画
        uploadContent.style.transition = 'all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)';
        uploadContent.style.opacity = '1';
        uploadContent.style.transform = 'translateY(0) scaleY(1)';
        
        uploadToggle.textContent = '▲';
        uploadToggle.style.transition = 'transform 0.3s ease';
        uploadToggle.style.transform = 'rotate(180deg)';
    } else {
        // 收起 - 使用平滑动画
        uploadContent.style.transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
        uploadContent.style.opacity = '0';
        uploadContent.style.transform = 'translateY(-10px) scaleY(0.9)';
        
        uploadToggle.style.transition = 'transform 0.2s ease';
        uploadToggle.style.transform = 'rotate(0deg)';
        
        setTimeout(() => {
            uploadContent.style.display = 'none';
            uploadToggle.textContent = '▼';
        }, 300);
    }
}

// DOM elements
document.addEventListener('DOMContentLoaded', function() {
    initializeUpload();
    initializeSearch();
    initializeFileActions();
    initializeBatchModeClickHandlers();
    // 初始化批量按钮状态
    updateBatchButtons();
});

// Upload functionality
function initializeUpload() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    
    if (!uploadArea || !fileInput) return;
    
    // Click to upload
    uploadArea.addEventListener('click', () => {
        fileInput.click();
    });
    
    // File input change
    fileInput.addEventListener('change', (e) => {
        handleFiles(e.target.files);
    });
    
    // Drag and drop
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });
    
    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('dragover');
    });
    
    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        handleFiles(e.dataTransfer.files);
    });
}

// Handle file upload
function handleFiles(files) {
    for (let file of files) {
        uploadFile(file);
    }
}

// Upload single file
function uploadFile(file) {
    const formData = new FormData();
    formData.append('file', file);
    
    // For duplicate files, we'll check first before showing upload notification
    const checkNotification = showNotification('正在检查文件...', 'info');
    
    fetch('/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Remove the checking notification
        if (checkNotification && checkNotification.parentNode) {
            checkNotification.remove();
        }
        
          
        if (data.success) {
            showNotification('上传成功!', 'success');
            addFileToGrid(data.file);
        } else {
            if (data.duplicate) {
                showNotification('文件已存在，无需重复上传', 'info');
            } else {
                showNotification('上传失败: ' + data.message, 'error');
            }
        }
    })
    .catch(error => {
        // Remove the checking notification
        if (checkNotification && checkNotification.parentNode) {
            checkNotification.remove();
        }
        showNotification('上传失败: ' + error.message, 'error');
    });
}

// Add file to grid
function addFileToGrid(file) {
    const fileGrid = document.getElementById('fileGrid');
    if (!fileGrid) return;
    
        
    const fileItem = createFileElement(file);
    fileGrid.insertBefore(fileItem, fileGrid.firstChild);
    currentFiles.unshift(file);
    
    // For images, check if thumbnail exists and load it
    if (file.image) {
        checkAndLoadThumbnail(fileItem, file);
    }
}

// Create file element
function createFileElement(file) {
    const div = document.createElement('div');
    div.className = 'file-item';
    div.dataset.fileId = file.id;
    
    // Always start with placeholder for images, then check for thumbnail
    const preview = file.image ? 
        `<div class="file-icon">🖼️</div>` :
        `<div class="file-icon">📄</div>`;
    
    div.innerHTML = `
        <div class="file-checkbox-container">
            <input type="checkbox" class="file-checkbox" data-file-id="${file.id}" onchange="updateSelectedCount()">
        </div>
        ${preview}
        <div class="file-info">
            <div class="file-name" title="${file.originalName}">${file.originalName}</div>
            <div class="file-size">${formatFileSize(file.size)}</div>
            <div class="file-actions">
                <button onclick="shareFile('${file.id}')" class="btn-share">分享</button>
                <button onclick="renameFile('${file.id}')" class="btn-primary">重命名</button>
                <button onclick="deleteFile('${file.id}')" class="btn-danger">删除</button>
            </div>
        </div>
    `;
    
    // If in batch mode, apply batch mode styling
    if (isBatchMode) {
        div.classList.add('batch-mode');
    }
    
    // Add click event for batch mode selection and image viewing
    div.addEventListener('click', function(e) {
        // Don't trigger if clicking on checkbox, buttons, or links
        if (e.target.type !== 'checkbox' && 
            e.target.tagName !== 'BUTTON' && 
            e.target.tagName !== 'A' &&
            !e.target.closest('button') && 
            !e.target.closest('a')) {
            
            if (isBatchMode) {
                // In batch mode: toggle checkbox selection
                const checkbox = this.querySelector('.file-checkbox');
                if (checkbox) {
                    checkbox.checked = !checkbox.checked;
                    updateSelectedCount();
                }
            } else {
                // Not in batch mode: view image if it's an image file
                const fileId = this.getAttribute('data-file-id');
                if (fileId) {
                    viewImageFromFileCard(fileId);
                }
            }
        }
    });
    
    return div;
}

// Format file size
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// Search functionality
function initializeSearch() {
    const searchForm = document.getElementById('searchForm');
    const searchInput = document.getElementById('searchInput');
    
    if (searchForm && searchInput) {
        searchForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const keyword = searchInput.value.trim();
            searchWithKeyword(keyword);
        });
    }
}

// File actions
function initializeFileActions() {
    // Action buttons will be bound dynamically
}

// Initialize batch mode click handlers for existing file items
function initializeBatchModeClickHandlers() {
    const existingFileItems = document.querySelectorAll('.file-item');
    existingFileItems.forEach(item => {
        // Remove existing event listener to avoid duplicates
        item.removeEventListener('click', handleBatchModeClick);
        // Add the batch mode click handler
        item.addEventListener('click', handleBatchModeClick);
    });
}

// Handle click on file cards
function handleBatchModeClick(e) {
    // Don't trigger if clicking on checkbox, buttons, or links
    if (e.target.type !== 'checkbox' && 
        e.target.tagName !== 'BUTTON' && 
        e.target.tagName !== 'A' &&
        !e.target.closest('button') && 
        !e.target.closest('a')) {
        
        if (isBatchMode) {
            // In batch mode: toggle checkbox selection
            const checkbox = this.querySelector('.file-checkbox');
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                updateSelectedCount();
            }
        } else {
            // Not in batch mode: view image if it's an image file
            const fileId = this.getAttribute('data-file-id');
            if (fileId) {
                viewImageFromFileCard(fileId);
            }
        }
    }
}

// Share file
function shareFile(fileId) {
    fetch('/share/create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'fileId=' + fileId
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showShareModal(data.shareUrl, data.token);
        } else {
            showNotification('创建分享链接失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        showNotification('创建分享链接失败: ' + error.message, 'error');
    });
}

// Show share modal
function showShareModal(shareUrl, token) {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    
    modal.innerHTML = `
        <div class="modal-content">
            <span class="modal-close" onclick="closeModal(this)">&times;</span>
            <h2>分享文件</h2>
            <div class="qr-container">
                <img src="/share/qrcode/${token}" alt="QR Code">
                <div class="share-info">
                    <p><strong>分享链接:</strong></p>
                    <p><a href="${shareUrl}" target="_blank">${shareUrl}</a></p>
                    <p style="display: none;"><strong>有效期:</strong> 30分钟</p>
                    <p style="display: none;"><strong>下载次数:</strong> 最多10次</p>
                </div>
                <button onclick="copyToClipboard('${shareUrl}')" class="btn">复制链接</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Close modal when clicking outside
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            closeModal(modal);
        }
    });
}

// Copy to clipboard
function copyToClipboard(text) {
    // 方法1: 尝试使用现代Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(() => {
            showNotification('链接已复制到剪贴板', 'success');
        }).catch(() => {
            fallbackCopyToClipboard(text);
        });
    } else {
        // 方法2: 使用传统方法
        fallbackCopyToClipboard(text);
    }
}

// 复制链接的备用方法
function fallbackCopyToClipboard(text) {
    // 创建一个临时的textarea元素
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';  // 防止页面滚动
    textarea.style.opacity = '0';      // 隐藏元素
    document.body.appendChild(textarea);
    
    try {
        // 选中文本
        textarea.select();
        textarea.setSelectionRange(0, 99999);  // 对于移动设备
        
        // 执行复制命令
        const successful = document.execCommand('copy');
        
        if (successful) {
            showNotification('链接已复制到剪贴板', 'success');
        } else {
            // 如果仍然失败，提供手动复制的选项
            showCopyFallbackModal(text);
        }
    } catch (err) {
        console.error('复制失败:', err);
        showCopyFallbackModal(text);
    } finally {
        // 移除临时元素
        document.body.removeChild(textarea);
    }
}

// 显示复制失败的备用方案
function showCopyFallbackModal(text) {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
    `;
    
    modal.innerHTML = `
        <div style="background: white; padding: 20px; border-radius: 8px; max-width: 500px; width: 90%;">
            <h3 style="margin: 0 0 15px 0; color: #333;">自动复制失败</h3>
            <p style="margin: 0 0 15px 0; color: #666;">请手动复制以下链接：</p>
            <div style="background: #f8f9fa; padding: 10px; border-radius: 4px; word-break: break-all; font-family: monospace; font-size: 14px; margin-bottom: 15px;">
                ${text}
            </div>
            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                <button onclick="this.closest('.modal').remove()" style="padding: 8px 16px; border: 1px solid #ddd; background: white; border-radius: 4px; cursor: pointer;">关闭</button>
                <button onclick="manualCopy('${text.replace(/'/g, "\\'")}')" style="padding: 8px 16px; border: none; background: #667eea; color: white; border-radius: 4px; cursor: pointer;">选择文本</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });
}

// 手动选择文本
function manualCopy(text) {
    const modal = document.querySelector('.modal');
    const textElement = modal.querySelector('div[style*="background: #f8f9fa"]');
    
    // 创建范围对象
    const range = document.createRange();
    range.selectNode(textElement);
    
    // 清除之前的选择
    window.getSelection().removeAllRanges();
    
    // 添加新的选择
    window.getSelection().addRange(range);
    
    showNotification('文本已选中，请按 Ctrl+C 复制', 'success');
}

// Close modal
function closeModal(element) {
    const modal = element.closest('.modal');
    if (modal) {
        modal.remove();
    }
}

// Rename file
function renameFile(fileId) {
    const newName = prompt('请输入新的文件名:');
    if (!newName) return;
    
    fetch('/files/rename', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'id=' + fileId + '&newName=' + encodeURIComponent(newName)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('重命名成功', 'success');
            location.reload();
        } else {
            showNotification('重命名失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        showNotification('重命名失败: ' + error.message, 'error');
    });
}

// Delete file
function deleteFile(fileId) {
    if (!confirm('确定要删除这个文件吗？')) return;
    
    fetch('/files/delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'id=' + fileId
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('删除成功', 'success');
            const fileItem = document.querySelector(`[data-file-id="${fileId}"]`);
            if (fileItem) {
                fileItem.remove();
            }
        } else {
            showNotification('删除失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        showNotification('删除失败: ' + error.message, 'error');
    });
}

// Show notification
function showNotification(message, type) {
    // Remove any existing notifications to prevent stacking
    const existingNotifications = document.querySelectorAll('.notification');
    existingNotifications.forEach(n => n.remove());
    
    const notification = document.createElement('div');
    notification.className = `notification alert alert-${type === 'error' ? 'danger' : type}`;
    notification.textContent = message;
    
    // Calculate position to avoid overlap with navbar
    const navbar = document.querySelector('.navbar');
    const navbarHeight = navbar ? navbar.offsetHeight : 0;
    notification.style.top = `${navbarHeight + 20}px`;
    
    document.body.appendChild(notification);
    
    // Auto remove after 3 seconds
    setTimeout(() => {
        notification.classList.add('fade-out');
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 300);
    }, 3000);
    
    // Return the notification element so it can be controlled
    return notification;
}

// View image from file card
function viewImageFromFileCard(fileId) {
    // First, we need to check if this is an image file
    fetch(`/files/${fileId}/info`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.image) {
                // It's an image file, show the image modal
                showImageModal(fileId, data.originalName);
            } else {
                // Not an image file, show notification
                showNotification('此文件不是图片文件，无法查看', 'info');
            }
        })
        .catch(error => {
            console.error('Error checking file type:', error);
            showNotification('无法查看文件', 'error');
        });
}

// Show image modal for viewing
function showImageModal(fileId, fileName) {
    
    // Create modal if it doesn't exist
    let modal = document.getElementById('imageModal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'imageModal';
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <button class="modal-close" onclick="closeImageModalInMonitoring()">&times;</button>
                <div class="modal-image-container">
                    <img id="modalImage" class="modal-image" src="" alt="">
                    <div id="imageLoading" class="image-loading-text" style="display: none;">加载中...</div>
                    <div id="imageError" style="color: #ff6b6b; text-align: center; display: none;">图片加载失败</div>
                </div>
                <div class="modal-qr-container">
                    <div id="qrLoading" class="qr-loading">生成二维码...</div>
                    <img id="modalQRCode" class="modal-qr-code" style="display: none;" src="" alt="下载二维码">
                    <div id="qrError" class="qr-error" style="display: none;">二维码生成失败</div>
                    <div class="qr-info">
                        <p>扫描二维码下载照片</p>
                        <p class="qr-expire" style="display: none;">30分钟有效 · 最多10次下载</p>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        
        // Close modal when clicking outside
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeImageModalInMonitoring();
            }
        });
    }
    
    // Get elements
    const modalImage = document.getElementById('modalImage');
    const loadingDiv = document.getElementById('imageLoading');
    const errorDiv = document.getElementById('imageError');
    const qrLoading = document.getElementById('qrLoading');
    const qrCode = document.getElementById('modalQRCode');
    const qrError = document.getElementById('qrError');
    const qrContainer = document.querySelector('.modal-qr-container');
    
    // Reset states - 隐藏所有内容，只显示加载中，整个二维码容器等图片加载完成后再显示
    loadingDiv.style.display = 'block';
    errorDiv.style.display = 'none';
    modalImage.style.display = 'none';
    qrContainer.style.display = 'none';  // 隐藏整个二维码容器
    
    // Set image source and show modal
    const imageUrl = `/files/view/${fileId}`;
    console.log('Loading image from:', imageUrl);
    
    modalImage.onload = function() {
        console.log('Image loaded successfully');
        loadingDiv.style.display = 'none';
        modalImage.style.display = 'block';

        // 如果是在监听模式，更新关闭按钮
        if (isMonitoringMode) {
            updateModalCloseButton(true);
        }

        // 图片加载完成后，开始生成二维码
        generateImageQRCode(fileId);
    };
    
    modalImage.onerror = function() {
        console.error('Failed to load image from:', imageUrl);
        loadingDiv.style.display = 'none';
        errorDiv.style.display = 'block';
        errorDiv.textContent = '图片加载失败，请检查文件是否存在';
    };
    
    modalImage.src = imageUrl;
    modalImage.alt = fileName;
    modal.style.display = 'flex';

    // Add ESC key listener
    document.addEventListener('keydown', handleImageModalESC);
}

// Close image modal
function closeImageModal() {
    const modal = document.getElementById('imageModal');
    if (modal) {
        modal.style.display = 'none';
    }
    // Remove ESC key listener
    document.removeEventListener('keydown', handleImageModalESC);
}

// Handle ESC key for image modal
function handleImageModalESC(event) {
    if (event.key === 'Escape') {
        closeImageModalInMonitoring();
    }
}

// Generate QR code for image download
function generateImageQRCode(fileId) {
    const qrLoading = document.getElementById('qrLoading');
    const qrCode = document.getElementById('modalQRCode');
    const qrError = document.getElementById('qrError');
    const qrContainer = document.querySelector('.modal-qr-container');
    
    // First create share link
    fetch('/share/create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'fileId=' + fileId
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Share link created successfully, now load QR code
            const qrImageUrl = '/share/qrcode/' + data.token;
            qrCode.onload = function() {
                // QR code loaded successfully
                qrLoading.style.display = 'none';
                qrCode.style.display = 'block';
                qrError.style.display = 'none';
                qrContainer.style.display = 'flex';
            };
            
            qrCode.onerror = function() {
                // Failed to load QR code
                qrLoading.style.display = 'none';
                qrError.style.display = 'block';
                qrError.textContent = '二维码加载失败';
            };
            
            // Start loading QR code
            qrCode.src = qrImageUrl;
        } else {
            // Failed to create share link
            qrLoading.style.display = 'none';
            qrError.style.display = 'block';
            qrError.textContent = '分享链接创建失败: ' + data.message;
        }
    })
    .catch(error => {
        console.error('Error creating share link:', error);
        qrLoading.style.display = 'none';
        qrError.style.display = 'block';
        qrError.textContent = '网络错误，请重试';
    });
}

// Check and load thumbnail for images
function checkAndLoadThumbnail(fileItem, file, retryCount = 0) {
    const maxRetries = 10; // Maximum 10 seconds of waiting
    const thumbnailUrl = `/thumbnails/${file.fileName}`;
    const img = new Image();
    
    
    img.onload = function() {
        // Thumbnail exists, replace the placeholder
        const placeholder = fileItem.querySelector('.file-icon');
        if (placeholder) {
            const imgElement = document.createElement('img');
            imgElement.src = thumbnailUrl;
            imgElement.alt = file.originalName;
            imgElement.className = 'file-preview';
            placeholder.parentNode.replaceChild(imgElement, placeholder);
        }
    };
    
    img.onerror = function() {
        // Thumbnail doesn't exist yet, retry after a delay
        if (retryCount < maxRetries) {
            setTimeout(() => {
                checkAndLoadThumbnail(fileItem, file, retryCount + 1);
            }, 1000);
        } else {
            // After max retries, just show a loading indicator or keep the placeholder
            const placeholder = fileItem.querySelector('.file-icon');
            if (placeholder) {
                placeholder.textContent = '🖼️';
                placeholder.title = '缩略图生成中...';
            }
        }
    };
    
    // Start checking
    img.src = thumbnailUrl;
}

// Utility functions
function formatDate(timestamp) {
    return new Date(timestamp).toLocaleString();
}

// Batch Operations Functions
function toggleBatchMode() {
    isBatchMode = !isBatchMode;
    const fileItems = document.querySelectorAll('.file-item');
    const batchModeButton = document.getElementById('btnBatchMode');
    
    if (isBatchMode) {
        // Enter batch mode
        fileItems.forEach(item => {
            item.classList.add('batch-mode');
        });
        batchModeButton.innerHTML = '<span class="batch-icon">✖️</span>退出批量操作';
        clearSelection();
        // Initialize click handlers when entering batch mode
        initializeBatchModeClickHandlers();
    } else {
        // Exit batch mode
        fileItems.forEach(item => {
            item.classList.remove('batch-mode', 'selected');
            const checkbox = item.querySelector('.file-checkbox');
            if (checkbox) {
                checkbox.checked = false;
            }
        });
        batchModeButton.innerHTML = '<span class="batch-icon">☑️</span>批量操作';
        selectedFiles.clear();
        updateSelectedCount();
    }
    updateBatchButtons();
}

function cancelBatchMode() {
    toggleBatchMode();
}

function updateSelectedCount() {
    const checkboxes = document.querySelectorAll('.file-checkbox:checked');
    selectedFiles.clear();
    checkboxes.forEach(checkbox => {
        selectedFiles.add(checkbox.getAttribute('data-file-id'));
    });
    
    const selectedCount = document.getElementById('selectedCount');
    selectedCount.textContent = `已选择 ${selectedFiles.size} 个文件`;
    
    // Update visual selection state
    const fileItems = document.querySelectorAll('.file-item');
    fileItems.forEach(item => {
        const fileId = item.getAttribute('data-file-id');
        if (selectedFiles.has(fileId)) {
            item.classList.add('selected');
        } else {
            item.classList.remove('selected');
        }
    });
    
    // Update batch buttons state
    updateBatchButtons();
}

function updateBatchButtons() {
    const btnBatchShare = document.getElementById('btnBatchShare');
    const btnBatchDelete = document.getElementById('btnBatchDelete');
    const btnCancelBatch = document.getElementById('btnCancelBatch');
    
    const hasSelection = selectedFiles.size > 0;
    const isInBatchMode = isBatchMode;
    
    // 批量分享和删除按钮：需要在批量模式且有选中文件时启用
    btnBatchShare.disabled = !(isInBatchMode && hasSelection);
    btnBatchDelete.disabled = !(isInBatchMode && hasSelection);
    
    // 取消按钮：需要在批量模式时启用
    btnCancelBatch.disabled = !isInBatchMode;
}

function clearSelection() {
    selectedFiles.clear();
    const checkboxes = document.querySelectorAll('.file-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    const fileItems = document.querySelectorAll('.file-item');
    fileItems.forEach(item => {
        item.classList.remove('selected');
    });
    updateSelectedCount();
}

function batchShare() {
    if (selectedFiles.size === 0) {
        showNotification('请先选择要分享的文件', 'error');
        return;
    }
    
    const fileIds = Array.from(selectedFiles).join(',');
    
    fetch('/share/batch-create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'fileIds=' + fileIds
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showShareModal(data.shareUrl, data.token);
            clearSelection();
            // 退出批量模式
            if (isBatchMode) {
                toggleBatchMode();
            }
        } else {
            showNotification('创建分享链接失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        showNotification('创建分享链接失败: ' + error.message, 'error');
    });
}

function batchDelete() {
    if (selectedFiles.size === 0) {
        showNotification('请先选择要删除的文件', 'error');
        return;
    }
    
    if (!confirm(`确定要删除选中的 ${selectedFiles.size} 个文件吗？`)) {
        return;
    }
    
    const fileIds = Array.from(selectedFiles).join(',');
    
    fetch('/files/batch-delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'fileIds=' + fileIds
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(`成功删除 ${data.deletedCount} 个文件`, 'success');
            // Remove deleted files from the grid
            selectedFiles.forEach(fileId => {
                const fileItem = document.querySelector(`[data-file-id="${fileId}"]`);
                if (fileItem) {
                    fileItem.remove();
                }
            });
            clearSelection();
            // 退出批量模式
            if (isBatchMode) {
                toggleBatchMode();
            }
        } else {
            showNotification('批量删除失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        showNotification('批量删除失败: ' + error.message, 'error');
    });
}

// 分页功能
function goToPage(page) {
    console.log('goToPage called with page:', page);
    
    // 获取当前URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const keyword = urlParams.get('keyword');
    
    // 构建新的URL
    let newUrl;
    if (keyword) {
        newUrl = '/search?keyword=' + encodeURIComponent(keyword) + '&page=' + page;
    } else {
        newUrl = '/?page=' + page;
    }
    
    console.log('Navigating to:', newUrl);
    
    // 跳转到新页面
    window.location.href = newUrl;
}

// 搜索时保持分页参数
function searchWithKeyword(keyword) {
    if (keyword && keyword.trim() !== '') {
        // 有关键词时跳转到搜索结果页
        window.location.href = '/search?keyword=' + encodeURIComponent(keyword) + '&page=1';
    } else {
        // 搜索框为空时：
        // 如果当前在搜索页面，则跳转到首页
        // 如果已经在首页，则刷新页面
        if (window.location.pathname === '/search') {
            window.location.href = '/';
        } else {
            // 重新加载首页，确保显示所有文件
            window.location.href = '/';
        }
    }
}

// ===== Live功能相关函数 =====

/**
 * 切换Live状态
 */
function toggleMonitoring() {
    if (isMonitoring) {
        // 停止Live
        stopMonitoring();
        updateMonitoringButton(false);
    } else {
        // 开始Live
        if (startMonitoring()) {
            updateMonitoringButton(true);
        }
    }
}

/**
 * 开始Live照片上传
 */
function startMonitoring() {
    try {
        // 关闭已存在的连接
        if (eventSource) {
            eventSource.close();
        }
        
        // 创建新的SSE连接
        eventSource = new EventSource('/api/stream');
        
        // 连接打开
        eventSource.onopen = function() {
            console.log('SSE连接已建立，开始Live模式照片上传');
            showNotification('已开启 Live 模式，等待照片上传...', 'info');
        };
        
        // 处理照片上传事件
        eventSource.addEventListener('photo-uploaded', function(event) {
            const photoData = JSON.parse(event.data);
            handleNewPhotoUploaded(photoData);
        });
        
        // 处理错误
        eventSource.onerror = function() {
            console.error('SSE连接错误');
            if (eventSource.readyState === EventSource.CLOSED) {
                showNotification('Live 连接已断开，请重新开启 Live', 'warning');
                stopMonitoring();
                updateMonitoringButton(false);
            }
        };
        
        return true;
    } catch (error) {
        console.error('启动 Live 失败:', error);
        showNotification('启动 Live 失败，请刷新页面后重试', 'error');
        return false;
    }
}

/**
 * 停止Live
 */
function stopMonitoring() {
    if (eventSource) {
        eventSource.close();
        eventSource = null;
    }
    
    // 重置Live模式标志
    isMonitoringMode = false;
    
    // 如果当前有照片模态框打开，则关闭它
    const modal = document.getElementById('imageModal');
    if (modal && modal.style.display === 'flex') {
        closeImageModal();
    }
    
    console.log('Live 已停止');
    showNotification('Live 模式已关闭', 'info');
}

/**
 * 处理新上传的照片
 */
function handleNewPhotoUploaded(photoData) {
    console.log('收到新照片:', photoData);

    // 设置Live模式标志
    isMonitoringMode = true;

    // 调用现有的显示照片函数，传递正确的参数
    showImageModalForLive(photoData.id, photoData.fileName);

    // 显示通知
    showNotification('Live 模式收到新照片: ' + photoData.originalName, 'success');
}

/**
 * Live模式下显示图片（确保正确的加载状态）
 */
function showImageModalForLive(fileId, fileName) {
    // Create modal if it doesn't exist
    let modal = document.getElementById('imageModal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'imageModal';
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <button class="modal-close" onclick="closeImageModalInMonitoring()">&times;</button>
                <div class="modal-image-container">
                    <img id="modalImage" class="modal-image" src="" alt="">
                    <div id="imageLoading" class="image-loading-text" style="display: none;">加载中...</div>
                    <div id="imageError" style="color: #ff6b6b; text-align: center; display: none;">图片加载失败</div>
                </div>
                <div class="modal-qr-container">
                    <div id="qrLoading" class="qr-loading">生成二维码...</div>
                    <img id="modalQRCode" class="modal-qr-code" style="display: none;" src="" alt="下载二维码">
                    <div id="qrError" class="qr-error" style="display: none;">二维码生成失败</div>
                    <div class="qr-info">
                        <p>扫描二维码下载照片</p>
                        <p class="qr-expire" style="display: none;">30分钟有效 · 最多10次下载</p>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        // Close modal when clicking outside
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeImageModalInMonitoring();
            }
        });
    }

    // Get elements
    const modalImage = document.getElementById('modalImage');
    const loadingDiv = document.getElementById('imageLoading');
    const errorDiv = document.getElementById('imageError');
    const qrLoading = document.getElementById('qrLoading');
    const qrCode = document.getElementById('modalQRCode');
    const qrError = document.getElementById('qrError');
    const qrContainer = document.querySelector('.modal-qr-container');

    // 重置状态 - 隐藏所有内容，只显示加载中，整个二维码容器等图片加载完成后再显示
    loadingDiv.style.display = 'block';
    errorDiv.style.display = 'none';
    modalImage.style.display = 'none';
    qrContainer.style.display = 'none';  // 隐藏整个二维码容器

    // 立即显示模态框，这样用户可以看到"加载中"
    modal.style.display = 'flex';

    // 设置图片源
    const imageUrl = `/files/view/${fileId}`;
    console.log('Live模式加载图片:', imageUrl);

    modalImage.onload = function() {
        console.log('Live模式图片加载成功');
        // 图片加载完成，隐藏加载中，显示图片
        loadingDiv.style.display = 'none';
        modalImage.style.display = 'block';

        // 更新关闭按钮
        updateModalCloseButton(true);

        // 图片加载完成后，开始生成二维码
        generateImageQRCode(fileId);
    };

    modalImage.onerror = function() {
        console.error('Live模式图片加载失败:', imageUrl);
        loadingDiv.style.display = 'none';
        errorDiv.style.display = 'block';
        errorDiv.textContent = '图片加载失败，请检查文件是否存在';
    };

    // 开始加载图片
    modalImage.src = imageUrl;
    modalImage.alt = fileName;

    // Add ESC key listener
    document.addEventListener('keydown', handleImageModalESC);
}

/**
 * 更新Live按钮状态
 */
function updateMonitoringButton(isActive) {
    const button = document.getElementById('btnStartMonitoring');
    const buttonText = document.getElementById('monitoringButtonText');
    
    if (isActive) {
        button.classList.add('active');
        buttonText.textContent = '停止 Live';
    } else {
        button.classList.remove('active');
        buttonText.textContent = '开启 Live';
    }
    isMonitoring = isActive;
}

/**
 * 更新模态框关闭按钮（Live模式）
 */
function updateModalCloseButton(isMonitoringMode) {
    const closeButton = document.querySelector('#imageModal .modal-close');
    if (closeButton) {
        if (isMonitoringMode) {
            closeButton.textContent = '退出 Live';
            closeButton.title = '退出 Live 模式';
            // 添加Live模式的特殊样式，使其看起来更像按钮
            closeButton.style.padding = '8px 16px';
            closeButton.style.fontSize = '14px';
            closeButton.style.fontWeight = '500';
            closeButton.style.backgroundColor = '#f87171';
            closeButton.style.color = 'white';
            closeButton.style.border = 'none';
            closeButton.style.borderRadius = '6px';
            closeButton.style.minWidth = '80px';
            closeButton.style.height = 'auto';
            closeButton.style.lineHeight = '1.4';
        } else {
            closeButton.innerHTML = '×';
            closeButton.title = '关闭';
            // 恢复原来的样式
            closeButton.style.padding = '';
            closeButton.style.fontSize = '';
            closeButton.style.fontWeight = '';
            closeButton.style.backgroundColor = '';
            closeButton.style.color = '';
            closeButton.style.border = '';
            closeButton.style.borderRadius = '';
            closeButton.style.minWidth = '';
            closeButton.style.height = '';
            closeButton.style.lineHeight = '';
        }
    }
}

/**
 * Live模式下的关闭模态框函数
 */
function closeImageModalInMonitoring() {
    if (isMonitoring) {
        // 如果是在Live模式，退出Live模式并关闭模态框
        stopMonitoring();
        updateMonitoringButton(false);
        updateModalCloseButton(false);
    } else {
        // 正常关闭
        closeImageModal();
    }
}

// 页面加载时重置Live状态
document.addEventListener('DOMContentLoaded', function() {
    // 重置所有Live相关的状态
    isMonitoring = false;
    isMonitoringMode = false;
    if (eventSource) {
        eventSource.close();
        eventSource = null;
    }
    // 重置按钮状态
    updateMonitoringButton(false);
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', function() {
    if (eventSource) {
        eventSource.close();
    }
});